<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>变量污染</title>
</head>
<body>
    
</body>
<script>
    var userId = 2;
    document.onclick  = function(){
        console.log('001:'+userId);
    }

    //ES5无块级，所以会产生变量污染，覆盖
    if(true)
    {
        var userId = 18;
        console.log('003:'+userId);
    }

//解决方法，匿名函数+立即执行

    (function name(){
        if(true)
        {
            var userId = 6;
            console.log('002:'+userId);
        }
    }());

    for(var i = 0; i<3;i++)
    {
        setTimeout(function (){console.log(new Date(),i)},1000);
    }

    //ES6   使用let 定义  就会产生块级作用域
    if(true)
    {
        let userId = 1;
        console.log(userId);
    }
</script>
</html>